# 导入中间件类
from starlette.middleware import Middleware

# 导入 CORS 中间件
from starlette.middleware.cors import CORSMiddleware

# 导入 HTTPS 重定向中间件
from starlette.middleware.httpsredirect import HTTPSRedirectMiddleware

# 导入可信主机中间件
from starlette.middleware.trustedhost import TrustedHostMiddleware

# 定义中间件列表
middleware = [
    # CORS 中间件：允许所有来源的跨域请求
    Middleware(CORSMiddleware, allow_origins=["*"]),
    # 可信主机中间件：只允许特定主机访问
    Middleware(TrustedHostMiddleware, allowed_hosts=["example.com"]),
    # HTTPS 重定向中间件：将 HTTP 请求重定向到 HTTPS
    Middleware(HTTPSRedirectMiddleware),
]


# 定义主函数
def main():
    # 导入必要的模块
    from starlette.applications import Starlette
    from starlette.routing import Route
    from starlette.responses import PlainTextResponse
    import uvicorn

    # 定义简单的处理函数
    async def homepage(request):
        return PlainTextResponse("Hello, World!")

    # 创建应用实例
    app = Starlette(routes=[Route("/", homepage)], middleware=middleware)
    # 启动服务器
    uvicorn.run(app, host="127.0.0.1", port=8000)


# 脚本入口
if __name__ == "__main__":
    main()
